package org.oss.client;


import org.apache.http.client.methods.HttpPost;
import org.oss.client.dto.BaseResponse;
import org.oss.client.dto.OssSecurityRequest;
import org.oss.client.dto.OssSecurityResponse;
import org.oss.client.dto.UploadRequest;
import org.oss.client.dto.UrlRequest;
import org.oss.client.dto.UrlResponse;

import com.aliyun.oss.common.utils.CodingUtils;
import com.aliyun.oss.model.PutObjectResult;
import com.oss.base.BaseConst;
import com.oss.base.OssMethod;
import com.oss.service.OSSUploadService;

public class OssClient extends DefaultClient{
	private OSSUploadService uploadService;

	protected OssClient(String schema, String ip, int port, String contextPath) {
		super(schema, ip, port,contextPath);
		initServices();
	}

	private void initServices() {
		uploadService=new OSSUploadService();
	}

	public OssClient(String ip, int port) {
		super("http", ip, port,"/oss-web/");
		initServices();
	}

	
	protected OssSecurityResponse getSTS(OssSecurityRequest req){
		CodingUtils.assertParameterNotNull(req.getUser(), "security request");
		CodingUtils.assertParameterNotNull(req.getPwd(), "security request");
		String json = this.mapper.toJson(req);
		HttpPost post = CreatePost(createURI(OssMethod.OSS_SECURITY),json);
		return (OssSecurityResponse) excuteAndParse(this.getHttpClient(), post, OssSecurityResponse.class);
	}
	
	public BaseResponse upload(UploadRequest req){
		try {
			OssSecurityResponse securityRes = getSTS(buildSecurityRquesr(req,OssMethod.PUT_OBJECT));
			PutObjectResult result=null;
			
			if(req.getFile() != null){
				result = uploadService.putBySTS(securityRes,req.getFile(),req.getFileName());
			}else{
				result = uploadService.putBySTS(securityRes,req.getInput(),req.getFileName());
			}
			
			BaseResponse res =new BaseResponse();
			res.setResultCode(BaseConst.RESPONSE_CODE_SUCCESS);
			res.setResultMsg(result.getETag());
			return res;
		} catch (Exception e) {
			return createErrRes(e);
		}
	}
	
	

	public UrlResponse getDownLoadUrl(UrlRequest req){
		String json = this.mapper.toJson(req);
		HttpPost post = CreatePost(createURI(OssMethod.OSS_URL),json);
		return (UrlResponse) excuteAndParse(this.getHttpClient(), post, UrlResponse.class);
	}
	

	
	
	
	

	
}
